// stores/websocketStore.js
import { defineStore } from 'pinia';
import { useHeaderStore } from "../stores/header"
import { WS_ADDRESS } from "../config";
import { useUserStore } from "../stores/user";

export const useWebSocketStore = defineStore('websocket', {
    state: () => ({
        ws: null,
        ack_ids: []
    }),
    actions: {
        connect(token) {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                ElMessage({
                    message: 'WebSocket is already connected',
                    type: 'warning',
                });
                return; // 防止重复连接
            }
            const webSocketUrl = WS_ADDRESS + "/" + token + "/";
            this.ws = new WebSocket(webSocketUrl);

            this.ws.onopen = (e) => {
                console.log('WebSocket opened', e);
            };

            this.ws.onclose = (e) => {
                console.log('WebSocket closed', e);
            };

            this.ws.onerror = (error) => {
                console.error('WebSocket error:', error);
            };

            this.ws.onmessage = (event) => {
                const headerStore = useHeaderStore();

                let data = event.data
                let msgObj = JSON.parse(data)
                if (msgObj.code === 0){
                    // 接受消息
                    console.log("受到消息: ", msgObj);
                    headerStore.state.messages.push({msg: msgObj.data.msg, sender: msgObj.data.sender, send_type: "friend"});
                    headerStore.state.addMessage = true;
                } else if (msgObj.code === -1){
                    // 批量获取消息, 消息确认
                    console.log("批量获取消息: ", msgObj);
                    headerStore.state.messages = msgObj.data;
                    this.ack_ids = [];
                    headerStore.state.messages.forEach(item => {
                        if (item.ack === 0){
                            this.ack_ids.push(item.id);
                        }
                    })
                    if (this.ack_ids.length !== 0){
                        console.log("发送确认消息：", this.ack_ids);
                        this.send({
                            method: "ack",
                            ack_ids: this.ack_ids
                        })
                    }
                } else if (msgObj.code === -2){
                    console.log("数据初始化：", msgObj);
                    // 消息初始化
                    const userStore = useUserStore();
                    msgObj.data.forEach(item => {
                        if (item.type === "friend"){
                            userStore.state.friendList.push(item);
                        }else if (item.type === "group"){
                            userStore.state.groupList.push(item);
                        }
                    })
                }
                else {
                    console.log("接受消息异常：", event);
                    // 失败
                    ElMessage({
                        message: msgObj.msg,
                        type: "error"
                    });
                }
            };
        },
        send(message) {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                this.ws.send(JSON.stringify(message));
            } else {
                console.error('WebSocket is not connected');
            }
        },
        disconnect() {
            if (this.ws) {
                this.ws.close();
                this.ws = null;
            }
        },
    },
});